const $models = require('mount-models')(__dirname);
const Resit = $models.resit;


// GET /resits/:stuID
module.exports.getResit = async (ctx, next) => {
    let stuID = ctx.params.stuID;

    if (!/^(2[0,1,3]\d{7})$/.test(stuID)) {
        ctx.status = 400;
        return ctx.body = {
            error: '学号格式不正确。请重新输入学号。'
        };
    }

    let resit = await new Promise((resolve, reject) => {
        Resit.find({ stuID }, '-_id', function (err, res) {
            if (err) {
                reject(err);
            } else {
                resolve(res);
            }
        });
    }).catch(err => {
        console.error(err);
    });

    if (0 === resit.length) {
        ctx.status = 404;
        return ctx.body = {
            error: '你没有需要重考的科目。'
        };
    }

    resit = {
        stuID: resit[0].stuID,
        stuName: resit[0].stuName,
        college: resit[0].college,
        'class': resit[0].class,
        courses: resit
    };
    resit = JSON.parse(JSON.stringify(resit));
    for (let i of resit.courses) {
        delete i.stuID;
        delete i.stuName;
        delete i.college;
        delete i.class;
    }

    const dateTime = new Date();
    console.log(
        `${resit.stuID}`,
        `${resit.stuName}`,
        `${resit.college}`,
        `${resit.class}`,
        `${resit.courses.length}门重考`,
        `${dateTime.toLocaleDateString()} ${dateTime.toLocaleTimeString()}`
    );

    return ctx.body = resit;
}